package hoge.memoriesalbum.post;

import hoge.memoriesalbum.R;
import hoge.memoriesalbum.util.BitmapUtil;
import hoge.memoriesalbum.util.Log;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.Intent;
import android.database.Cursor;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.AsyncTask;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.AdapterView.OnItemClickListener;

/**
 * POST画像をGrid表示(カメラ撮影付き)
 * 
 * @author hyoromo
 */
public class PostGridActivity extends Activity implements OnItemClickListener {
    static final int REQUEST_PICTURE = 1;
    static final int BITMAP_SCALE = 4;
    private static Activity mActivity;
    private static Context mContext;
    private static ImageAdapter mAdapter;
    private static String[] mData;
    private static int mBitmapWidth;
    private static int mBitmapHeight;

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.post_grid);
        mActivity = this;
        mContext = getApplicationContext();
        mBitmapWidth = getWallpaperDesiredMinimumWidth() / BITMAP_SCALE;
        mBitmapHeight = getWallpaperDesiredMinimumHeight() / BITMAP_SCALE;

        new ImageLoadTask().execute();
    }

    /**
     * 画像読込タスク
     * 
     * @author hyoromo
     */
    private class ImageLoadTask extends AsyncTask<Void, Void, Void> {
        private ProgressDialog mProgressDialog;

        @Override
        protected void onPreExecute() {
            String title = getResources().getString(R.string.post_load_prrogress_dialog_title);
            String mes = getResources().getString(R.string.post_load_prrogress_dialog_mes);
            mProgressDialog = ProgressDialog.show(mActivity, title, mes, true);
        }

        @Override
        protected final Void doInBackground(Void... v) {
            // 表示画像のパス取得
            imagePath();

            // GridViewに表示させるためのアダプターを作成
            mAdapter = new ImageAdapter();
            for (String path : mData) {
                mAdapter.add(listDatas(path));
                Log.v(path);
            }

            return null;
        }

        /**
         * 画面上に表示させる画像のパスを取得
         */
        private void imagePath() {
            // 端末内の全画像データのフルパスを取得
            Uri image_uri = MediaStore.Images.Media.EXTERNAL_CONTENT_URI;
            Cursor cursor = getContentResolver().query(image_uri, null, null, null, null);
            mData = new String[cursor.getCount()];
            for (int i = 0; i < mData.length; i++) {
                cursor.moveToPosition(mData.length - (i + 1));
                mData[i] = cursor.getString(1);
            }
            cursor.close();
        }

        private ListData listDatas(String data) {
            ListData listData = new ListData();
            listData.url = data;
            listData.bitmap = BitmapUtil.scaleBitmap(data, mBitmapWidth, mBitmapHeight);

            return listData;
        }

        @Override
        protected final void onPostExecute(Void v) {
            // GridViewを作成してアダプターをセット
            GridView gv = (GridView) findViewById(R.id.post_grid);
            gv.setOnItemClickListener((OnItemClickListener) mActivity);
            gv.setAdapter(mAdapter);

            mProgressDialog.dismiss();
        }
    }

    /**
     * ArrayAdapterを拡張したクラス。 画像を一覧表示させている。
     * 
     * @author hyoromo
     */
    private class ImageAdapter extends ArrayAdapter<ListData> {
        private final LayoutInflater mInflater;

        ImageAdapter() {
            super(mContext, 0);
            mInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        }

        /**
         * 画面に表示される毎に呼び出される
         */
        final public View getView(int position, View convertView, ViewGroup parent) {
            ListStorage listStorage;
            View row = convertView;

            // Listの画像イメージを作成
            if (row == null || row.getTag() == null) {
                row = mInflater.inflate(R.layout.post_grid_rowdata, parent, false);
                listStorage = new ListStorage();
                listStorage.img = (ImageView) row.findViewById(R.id.post_grid_img);
                listStorage.img.setLayoutParams(new GridView.LayoutParams(85, 85));
                row.setTag(listStorage);
            } else {
                listStorage = (ListStorage) row.getTag();
            }

            // Listに画像設定
            ListData listData = getItem(position);
            listStorage.url = listData.url;
            listStorage.img.setImageBitmap(listData.bitmap);

            return row;
        }
    }

    public final class ListData {
        public String url;
        public Bitmap bitmap;
    }

    private class ListStorage {
        ImageView img;
        String url;
    }

    /**
     * 画像がクリックされたら呼ばれる
     */
    public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
        ImageView img = (ImageView) v.findViewById(R.id.post_grid_img);
        ListStorage listStorage = (ListStorage) img.getTag();
        Log.v(listStorage.url);

        // コールバック付きで遷移
        Intent intent = new Intent(mContext, PostSelectActivity.class);
        intent.putExtra("PATH", listStorage.url);
        startActivity(intent);
    }

    /**
     * カメラで撮影するボタンが押されたら呼ばれる
     */
    public void onCameraClick(View v) {
        Intent intent = new Intent(Intent.ACTION_MAIN);
        intent.setClassName("com.android.camera", "com.android.camera.Camera");
        intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
        startActivityForResult(intent, REQUEST_PICTURE);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        Log.v("result");
        if (requestCode == REQUEST_PICTURE) {
            // リストを再読み込み
            mAdapter.clear();
            new ImageLoadTask().execute();
        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();

        mContext = null;
        mData = null;
    }
}